﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Collections;
using Sencha.Serialization;

namespace Sencha.Direct.Client
{
	public abstract partial class RpcConnection
	{
		/// <summary>
		/// Response on request
		/// </summary>
		[DataContract]
		public sealed class IncomingResponse
		{
			/// <summary>
            /// Request type - rpc
			/// </summary>
			[DataMember(Name = "type")]
			public string Type { get; set; }

			/// <summary>
			/// Request #
			/// </summary>
			[DataMember(Name = "tid")]
			public int TransactionId { get; set; }

			/// <summary>
			/// Request action name
			/// </summary>
			[DataMember(Name = "action")]
			public string Action { get; set; }

			/// <summary>
			/// Request controller name
			/// </summary>
			[DataMember(Name = "method")]
			public string Controller { get; set; }

			/// <summary>
			/// Request error
			/// </summary>
			[DataMember(Name = "error")]
			public JsError Error { get; set; }

			/// <summary>
			/// Request result
			/// </summary>
			[DataMember(Name = "result")]
			public JsonString Result { get; set; }

			/// <summary>
			/// Get string representation of request
			/// </summary>
			public override string ToString()
			{
				return string.Format("#{0} {1}.{2}", this.TransactionId, this.Controller, this.Action);
			}
		}

		private bool IsErrorResult(object p)
		{
			if (!(p is IDictionary<string,object>))
				return false;

			var error = p as IDictionary<string, object>;
			if (error.ContainsKey("message") && error.ContainsKey("stackTrace") && error.ContainsKey("name"))
				return true;
			else
				return false;
		}
		private Exception GetErrorFromResult(object p)
		{
			if (!(p is IDictionary<string, object>))
				return null;

			var error = p as IDictionary<string, object>;
			return new Exception(error["message"] as string ?? "an error");
		}

	}
}
